package com.srcbox.file.util

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.service.autofill.TextValueSanitizer
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.srcbox.file.R
import org.w3c.dom.Text
import java.text.DecimalFormat

class EggDialog(val context: Context) {
    var view: View? = null
    var dialog: BottomSheetDialog? = null
    var versionName: String = "1.0"
    var versionLink: String = ""

    @SuppressLint("SetTextI18n")
    fun create(diaType: Int): EggDialog {
        isUse = true
        dialog = BottomSheetDialog(context)
        view = View.inflate(context, R.layout.egg_dialog, null)
        dialog?.setContentView(view!!)
        val parent = view?.parent as ViewGroup
        parent.setBackgroundResource(android.R.color.transparent)
        dialog?.show()
        val packInfo = context.applicationContext.packageManager.getPackageInfo(
            context.packageName,
            0
        )
        val versionName = packInfo.versionName
        val versionCode = packInfo.versionCode
        view?.findViewById<TextView>(R.id.curr_ver)?.text = "当前版本：$versionName#$versionCode"
        initEvent(diaType)
        return this
    }

    private fun initEvent(diaType: Int) {
        view?.findViewById<CardView>(R.id.dia_btn_on)?.setOnClickListener {
            when (diaType) {
                DAY_DIALOG -> {
                    dialog?.cancel()
                }

                UPDATE_DIALOG -> {
                    val btnT = view?.findViewById<TextView>(R.id.btn_text)
                    btnT?.text = "准备中..."
                    FileDownloader.setup(context)
                    val fileName = "updateApp$versionName.apk"
                    val downPath = "${context.filesDir}/apk/$fileName"
                    FileDownloader.getImpl().create(versionLink)
                        .setPath(downPath)
                        .setListener(object : FileDownloadListener() {
                            override fun pending(
                                task: BaseDownloadTask,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                println("a")
                                btnT?.text = "等待中..."
                            }

                            override fun connected(
                                task: BaseDownloadTask,
                                etag: String,
                                isContinue: Boolean,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                btnT?.text = "启动中..."
                            }

                            override fun progress(
                                task: BaseDownloadTask,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                val pro = soFarBytes.toFloat() / totalBytes.toFloat()
                                btnT?.text = DecimalFormat(".00").format((pro * 100.0))
                                println("c$soFarBytes")
                            }

                            override fun blockComplete(task: BaseDownloadTask) {}
                            override fun retry(
                                task: BaseDownloadTask,
                                ex: Throwable,
                                retryingTimes: Int,
                                soFarBytes: Int
                            ) {
                                println("d")
                            }

                            override fun completed(task: BaseDownloadTask) {
                                btnT?.text = "点击安装"
                                if (Build.VERSION.SDK_INT >= 26) {
                                    if (!context.packageManager.canRequestPackageInstalls()) {
                                        EggUtil.toast(context, "请授权")
                                        EggUtil.startInstallPermissionSettingActivity(context)
                                        return
                                    }
                                }
                                EggUtil.openAndroidFile(context, downPath)
                            }

                            override fun paused(
                                task: BaseDownloadTask,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                println("e")
                            }

                            override fun error(
                                task: BaseDownloadTask,
                                e: Throwable
                            ) {
                                EggUtil.toast(context, "出现错误：$e")
                            }

                            override fun warn(task: BaseDownloadTask) {}
                        }).start()
                }
            }
        }
    }

    fun setTitle(con: String): EggDialog {
        view?.findViewById<TextView>(R.id.dia_title)?.text = con
        return this
    }

    fun setContent(con: String): EggDialog {
        view?.findViewById<TextView>(R.id.dia_con)?.text = con
        return this
    }

    @SuppressLint("SetTextI18n")
    fun setNewVer(versionName: String, versionCode: String, versionLink: String): EggDialog {
        view?.findViewById<TextView>(R.id.new_ver)?.text = "最新版本：$versionName#$versionCode"
        this.versionName = versionName
        this.versionLink = versionLink
        return this
    }

    fun hideVer(): EggDialog {
        view?.findViewById<LinearLayout>(R.id.dia_ver)?.visibility = View.GONE
        return this
    }

    companion object {
        const val DAY_DIALOG = 1
        const val UPDATE_DIALOG = 2
        var isUse = false
    }
}